<template>
  <div class="container">
    <el-card shadow="hover">
      <div slot="header" style="font-size:18px;font-weight:bold">
        <i class="el-icon-edit"></i> 编辑常见害虫
      </div>

      <el-form :model="form"
               :rules="rules"
               ref="ruleForm"
               label-width="130px"
               style="margin-top:30px">

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="害虫名称" prop="name">
              <el-input v-model="form.name" placeholder="例如：棉叶螨"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="分类" prop="categories">
              <el-select v-model="form.categories"
                         multiple
                         placeholder="请选择分类（可多选）"
                         style="width:100%">
                <el-option v-for="item in categoryOptions"
                           :key="item.id"
                           :label="item.name"
                           :value="item.name"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="基本信息" prop="basicInformation">
          <el-input v-model="form.basicInformation" type="textarea" :rows="2"/>
        </el-form-item>
        <el-form-item label="形态特征" prop="morphologicalCharacteristics">
          <el-input v-model="form.morphologicalCharacteristics" type="textarea" :rows="2"/>
        </el-form-item>
        <el-form-item label="生活习性" prop="livingHabits">
          <el-input v-model="form.livingHabits" type="textarea" :rows="2"/>
        </el-form-item>
        <el-form-item label="发生规律" prop="occurrencePattern">
          <el-input v-model="form.occurrencePattern" type="textarea" :rows="2"/>
        </el-form-item>
        <el-form-item label="危害特点" prop="hazardCharacteristics">
          <el-input v-model="form.hazardCharacteristics" type="textarea" :rows="2"/>
        </el-form-item>
        <el-form-item label="防治方法" prop="controlMethods">
          <el-input v-model="form.controlMethods" type="textarea" :rows="2"/>
        </el-form-item>

        <!-- 图片管理 -->
        <el-form-item label="害虫图片">
          <el-upload ref="upload"
                     name="file"
                     :file-list="fileList"
                     multiple
                     accept="image/*"
                     list-type="picture-card"
                     :action="uploadAction"
                     :before-upload="beforeUpload"
                     :on-success="handleSuccess"
                     :on-error="handleError"
                     :on-remove="handleRemove"
                     :auto-upload="false">
            <i class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">支持多选，建议 1:1，单张≤2MB</div>
          </el-upload>
        </el-form-item>

        <el-form-item class="footer-buttons">
          <el-button type="primary" icon="el-icon-check" @click="update" :loading="loading">保存修改</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'
import Cookies from 'js-cookie'

export default {
  name: 'EditPest',
  data() {
    return {
      loading: false,
      form: {
        id: null,
        name: '',
        basicInformation: '',
        morphologicalCharacteristics: '',
        livingHabits: '',
        occurrencePattern: '',
        hazardCharacteristics: '',
        controlMethods: '',
        categories: [],
        cover: [] // 添加cover字段用于存储图片URL
      },
      rules: {
        name: [{ required: true, message: '请输入害虫名称', trigger: 'blur' }],
        categories: [{ type: 'array', min: 1, message: '请至少选择一个分类', trigger: 'change' }],
        basicInformation: [{ required: true, message: '请输入基本信息', trigger: 'blur' }],
        morphologicalCharacteristics: [{ required: true, message: '请输入形态特征', trigger: 'blur' }],
        livingHabits: [{ required: true, message: '请输入生活习性', trigger: 'blur' }],
        occurrencePattern: [{ required: true, message: '请输入发生规律', trigger: 'blur' }],
        hazardCharacteristics: [{ required: true, message: '请输入危害特点', trigger: 'blur' }],
        controlMethods: [{ required: true, message: '请输入防治方法', trigger: 'blur' }]
      },
      categoryOptions: [],
      fileList: [],          // 回显用
      uploadUrls: [],        // 新上传地址
      uploadAction: ''
    }
  },
  created() {
    this.form.id = this.$route.query.id
    // 确保使用正确的URL，包含实际的害虫ID
    this.uploadAction = `http://localhost:9090/api/image/upload/${this.form.id}`
    this.loadDetail()
    this.loadCategories()
  },

  methods: {
    /* 拉取单条记录 */
    loadDetail() {
      request.get(`/pest/${this.form.id}`).then(res => {
        if (res.code === '200') {
          Object.assign(this.form, res.data)
          // 使用新接口获取图片列表
          request.get(`/image/list/${this.form.id}`).then(imgRes => {
            if (imgRes.code === '200') {
              // 封面图片回显（已有图片）
              this.form.cover = imgRes.data || [];
              if (imgRes.data && imgRes.data.length > 0) {
                this.fileList = imgRes.data.map((url, idx) => ({
                  name: `image_${idx}`,
                  url: url
                }))
                this.uploadUrls = [...imgRes.data] // 创建副本避免直接修改
              } else {
                this.fileList = [];
                this.uploadUrls = [];
              }
            } else {
              console.error('获取图片列表失败:', imgRes.msg);
            }
          }).catch(error => {
            console.error('获取图片列表失败:', error);
          });
        }
      })
    },
    /* 分类下拉 */
    loadCategories() {
      request.get('/category/tree').then(res => {
        this.categoryOptions = this.flatTree(res.data || [])
      })
    },
    flatTree(tree) {
      let arr = []
      tree.forEach(n => {
        arr.push({ id: n.id, name: n.name })
        if (n.children && n.children.length) arr = arr.concat(this.flatTree(n.children))
      })
      return arr
    },
    /* 更新提交 */
    update() {
      this.$refs.ruleForm.validate(valid => {
        if (!valid) return
        this.loading = true

        // 提交上传的文件
        if (this.$refs.upload && this.$refs.upload.uploadFiles && this.$refs.upload.uploadFiles.length > 0) {
          // 有文件需要上传
          this.$refs.upload.submit();
          // 等待上传完成后再提交表单
        } else {
          // 没有新文件需要上传，直接提交表单
          this.submitForm();
        }
      })
    },
    submitForm() {
      // ✅ 关键：把最新的图片地址塞进表单
      this.form.cover = [...this.uploadUrls]

      console.log('提交表单：', this.form) // 调试日志

      request.put('/pest/update', this.form).then(res => {
        if (res.code === '200') {
          this.$notify.success('修改成功')
          this.$router.push('/verminList')
        } else {
          this.$message.error(res.msg || '更新失败')
        }
        this.loading = false
      }).catch(err => {
        this.$message.error(err.msg || '请求失败')
        this.loading = false
      })
    },
    /* 上传相关方法 */
    beforeUpload(file) {
      const isImg = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImg) this.$message.error('只能上传 JPG/PNG 图片')
      if (!isLt2M) this.$message.error('单张图片不超过 2MB')
      return isImg && isLt2M
    },
    handleSuccess(res, file, fileList) {
      if (res.code === '200') {
        // ✅ 把新图地址塞进 uploadUrls
        if (Array.isArray(res.data)) {
          this.uploadUrls.push(...res.data)
        } else {
          this.uploadUrls.push(res.data)
        }
        this.$notify.success('图片上传成功')
        // 检查是否所有文件都上传完成
        if (fileList.every(f => f.status === 'success')) {
          this.submitForm();
        }
      } else {
        this.$message.error(res.msg || '图片上传失败')
        this.loading = false;
      }
    },
    handleError(err, file, fileList) {
      console.error('上传失败:', err)
      this.$message.error('图片上传失败，请重试')
      this.loading = false;
    },
    handleRemove(file) {
      const idx = this.uploadUrls.indexOf(file.url)
      if (idx > -1) this.uploadUrls.splice(idx, 1)
    },
    /* 重置 */
    reset() {
      this.loadDetail() // 重新回填原数据
      this.$message.info('已重置为原始数据')
    }
  }
}
</script>

<style scoped>
.container{width:80%;margin:20px auto}
.avatar-uploader-icon{font-size:28px;color:#8c939d;width:148px;height:148px;line-height:148px;text-align:center}
.footer-buttons{text-align:center;margin-top:30px}
</style>
